package com.swdegao.iot.netty.udp.server;

import com.swdegao.iot.netty.entity.Ports;
import com.swdegao.iot.netty.udp.server.guoxinudp.GuoXinUdpNettyServerChannelInitializer;
import com.swdegao.iot.netty.utils.ExceptionUitls;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.epoll.EpollChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class NettyUDPServer {
	// 定义一个全局的记录器，通过LoggerFactory获取
	private final static Logger logger = LoggerFactory.getLogger(NettyUDPServer.class);
//	private EventLoopGroup bossGroup;
//	public static Channel serverChannel;
	public NettyUDPServer() {
//		this.bossGroup = new NioEventLoopGroup();
	}

	public void doStart(Ports port) {
		try {
			start(port);
		} catch (Exception e) {
			logger.debug("UDPServer start error: " + e.getMessage());
		}
	}

	/**
	 * UDP启动管理
	 * @param port
	 */
	private void start(Ports port) {

//		deGao_udp_channelInit(port.getDegao_udp_port());//德高大表UDP

		//国信UDP
		if(null != port.getGuoxin_udp_port() && port.getGuoxin_udp_port() > 0){
			guoxin_udp_channelInit(port.getGuoxin_udp_port());
		}

	}

	//德高大表UDP
	private void deGao_udp_channelInit(Integer port){
		EventLoopGroup bossGroup = new NioEventLoopGroup();
		Channel serverChannel = null;
		try {

			// start server udp
			logger.info("德高 udp Server start !端口号：" + port);
			Bootstrap b = new Bootstrap();
			b.group(bossGroup).channel(NioDatagramChannel.class).handler(new NettyServerChannelInitializer());
			b.option(EpollChannelOption.SO_BROADCAST, true)// 开启广播模式
					.option(EpollChannelOption.SO_RCVBUF, 2048 * 1024)// 设置UDP读缓冲区为2M
					.option(EpollChannelOption.SO_SNDBUF, 1024 * 1024);// 设置UDP写缓冲区为1M

			logger.info("德高 udp Server 开始绑定端口！");
			ChannelFuture f = b.bind(port).sync();
			// 获取channel通道
			serverChannel = f.channel();
			// 等待服务器 socket 关闭 。
			// 这不会发生，可以优雅地关闭服务器。
			f.channel().closeFuture().sync();

			logger.info("德高 udp Server start OK!");
		} catch (Exception ex) {
			logger.info("德高 udp Server start error: " + ex.getMessage());
			if (serverChannel != null) {
				serverChannel.close();
			}
			bossGroup.shutdownGracefully();
			ex.printStackTrace();
		} finally {
			//bossGroup.shutdownGracefully();

		}
	}

	//国信集中器UDP
	private void guoxin_udp_channelInit(Integer port){
		EventLoopGroup bossGroup = new NioEventLoopGroup();
		Channel serverChannel = null;
			try {
				// start server udp
				logger.info("国信 udp Server 开始启动");
				Bootstrap b = new Bootstrap();

				b.group(bossGroup).channel(NioDatagramChannel.class).handler(new GuoXinUdpNettyServerChannelInitializer());
				b.option(EpollChannelOption.SO_BROADCAST, true)// 开启广播模式
						//.option(EpollChannelOption.SINGLE_EVENTEXECUTOR_PER_GROUP,false)
//						.option(ChannelOption.SO_REUSEADDR, true)
						.option(EpollChannelOption.SO_RCVBUF, 2048 * 1024)// 设置UDP读缓冲区为2M
						.option(EpollChannelOption.SO_SNDBUF, 1024 * 1024);// 设置UDP写缓冲区为1M
				// ChannelFuture f = b.bind(port).sync();
				// f.channel().closeFuture().await();

				logger.info("国信 udp Server 开始绑定端口：" + port);
				Thread.sleep(1000);
				ChannelFuture f = b.bind(port).sync();
				logger.info("国信 udp Server 成功绑定端口：" + port);
				// 获取channel通道
				serverChannel = f.channel();
				// 等待服务器 socket 关闭 。
				// 这不会发生，可以优雅地关闭服务器。
				f.channel().closeFuture().sync();

				logger.info("国信 udp Server start OK!");
			} catch (Exception ex) {
				logger.info("国信 udp Server start error: " + ex.getMessage()+ ExceptionUitls.getExceptionInfo(ex));
				if (serverChannel != null) {
					serverChannel.close();
				}
				bossGroup.shutdownGracefully();
				logger.info("国信 udp Server is shut down");
				ex.printStackTrace();

			} finally {
				//bossGroup.shutdownGracefully();

			}

	}



}
